//
//  XSQViewController.swift
//  WeiBo
//
//  Created by 许世强 on 2017/3/27.
//  Copyright © 2017年 许世强. All rights reserved.
//

import UIKit

class XSQNavigationController: UINavigationController,UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        //设置边缘手势代理
        self.interactivePopGestureRecognizer?.delegate = self
        
    }

   //监听push操作
    //重写pushViewController方法
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        
        //大于0,表示有控制器
        if self.viewControllers.count > 0{
            
            if self.viewControllers.count == 1{
            
                //获取上一个控制器的标题
                let title = self.viewControllers.first?.title
                
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title:title!,imageName:"navigationbar_back_withtext",target:self,action:#selector(leftAction))
                
                viewController.navigationItem.title = "当前显示的是第\(self.viewControllers.count + 1)级控制器"
            } else {
            
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title:"返回",imageName:"navigationbar_back_withtext",target:self,action:#selector(leftAction))
                
                viewController.navigationItem.title = "当前显示的是第\(self.viewControllers.count + 1)级控制器"
            }
            
            //隐藏tabBar, 在非根控制器的时候
            viewController.hidesBottomBarWhenPushed = true
        }
        
        super.pushViewController(viewController, animated: animated)
    }
    
    @objc private func leftAction(){
        
        self.popViewController(animated: true)
    }
    
    //实现边缘手势的代理方法
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        //根视图的时候,不需要开启边缘手势,否则会有bug
        if self.viewControllers.count == 1{
        
            return false
        
        }
        
        return true
    }
}
